package com.sqin.taskflow.queue;

import com.sqin.taskflow.config.TaskFlowConfig;
import com.sqin.taskflow.task.AbsTask;
import com.sqin.taskflow.utils.ValidateUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Slf4j
public class TaskFlow {

    private List<AbsTask> taskQueue = new ArrayList<>();

    public void put(AbsTask task){
        taskQueue.add(task);
    }

    public void run() throws ExecutionException, InterruptedException, TimeoutException {
        ThreadPoolExecutor customThreadPool = new ThreadPoolExecutor(
                TaskFlowConfig.corePoolSize,
                TaskFlowConfig.maximumPoolSize,
                TaskFlowConfig.keepAliveTime,
                TaskFlowConfig.unit,
                TaskFlowConfig.workQueue);
        CompletableFuture<Void> future = null;
        for (int i=0;i<taskQueue.size();i++){
//            log.info("task-{}-{}",taskQueue.get(i).getName(),i);
            if(i==0){
                future = CompletableFuture.runAsync(taskQueue.get(i),customThreadPool);
            }else{
                future = future.thenRun(taskQueue.get(i));
            }
        }
        future.get(10, TimeUnit.SECONDS);
    }

}
